extends Control
class_name InputComponent
#@onready var text_edit: TextEdit = $Control/InputText
@onready var text_edit: TextEdit = $"."
@export var FixY: float
@onready var label: Label = $"../LestPowder"
@onready var bullet_container: DynamicContainer = $BulletContainer

# 预加载弹出效果场景（需先创建）
const POP_LABEL_SCENE = preload("res://scene/ItemScene/TextEffect/DeleteEffect/DeleteEffect.tscn")
const TEXT_BULLET_SCENE = preload("res://scene/Track/TextBullet/TextBullet.tscn")

# 字符串相关变量
var last_key_name = ""        # 存储键的名称
var previous_text := ""    
var previous_caret_column := 0    # 存储按下前的光标列位置
var keycode 

# 输入数据相关变量
var CurTextPowder: int

#signal PlayerShoot
signal bullet_shoot(bullet_nums : int)

func _ready() -> void:
	#previous_text = text_edit.text
	text_edit.text_changed.connect(_on_text_edit_text_changed)
	connect("gui_input", Callable(self, "_input"))
	CurTextPowder = PlayerState.LocalTextPowder
	
	

func _process(delta: float) -> void:
	label.text = "当前字符火药值为：" + str(CurTextPowder)

# 由于上下文的关系，input函数会在信号函数前被调用，所以在处理输入的时候，输入时需要立马执行的逻辑需要写在
# input函数内，输入后的逻辑写在信号内。 
func _input(event):

	if event.is_action_pressed("SwitchInputState"):
		get_viewport().set_input_as_handled()  # 阻止事件继续传播
		_change_input_state()

	if event.is_action_pressed("Shoot") and PlayerState.CurrentInputState == PlayerState.InputState.Shoot:
		var text_num = text_edit.text.length()
		bullet_shoot.emit(text_num)
		bullet_container.remove_back_child()
		
		#PlayerShoot.emit()
		#get_viewport().set_input_as_handled()  # 阻止事件继续传播

	# 如果字符火药值不够则不允许输入，弹警告
	if event is InputEventKey and event.pressed:
		keycode = event.keycode
		match keycode:
			KEY_BACKSPACE:
				previous_text = text_edit.text
				previous_caret_column = text_edit.get_caret_column()
				return
			KEY_ENTER, KEY_KP_ENTER:
				# 拦截回车键，阻止默认换行行为
				get_viewport().set_input_as_handled()
				_handle_enter()  # 手动调用回车处理逻辑
				return

func _on_text_edit_text_changed() -> void:
	match keycode:
		KEY_BACKSPACE:
			_handle_backspace()
		KEY_ENTER, KEY_KP_ENTER:
			# 回车键已在 _input 中处理，这里无需额外逻辑
			return
		_:
			if CurTextPowder > 0:
				CurTextPowder -= 1  # 消耗火药值
				if CurTextPowder == 0:
					previous_text = text_edit.text
					previous_caret_column = text_edit.get_caret_column()
			else:
				# 回滚到之前的状态（防止通过粘贴等方式绕过限制）
				text_edit.text = previous_text
				text_edit.set_caret_column(previous_caret_column)    
				_show_powder_warning()
				return 

func _handle_enter() -> void:
	var text: String = text_edit.text.strip_edges()  # 去除首尾空白
	if text == "":
		#print("输入为空，不创建子弹")
		return
	
	# 非空时创建子弹
	#print("非空，创建子弹")
	_create_textbullet(text)
	text_edit.clear()
	previous_text = ""

func _handle_backspace() -> void:
	previous_text = text_edit.text
	previous_caret_column = text_edit.get_caret_column()
	
	var deleted_char: String
	if previous_caret_column > 0 && previous_caret_column <= previous_text.length():
		deleted_char = previous_text.substr(previous_caret_column - 1, 1)
		
	_create_delete_effect(deleted_char)

func _create_textbullet(str: String) -> void:
	if str == "":
		#print("警告：尝试创建空文本子弹")
		return
	var bullet = TEXT_BULLET_SCENE.instantiate() as TextBullet
	bullet.set_bullet_data(str)
	bullet_container.add_custom_child(bullet)

func _create_delete_effect(char: String) -> void:
	var pop_obj = POP_LABEL_SCENE.instantiate()
	pop_obj.text = char
	
	var caret_pos = text_edit.get_caret_draw_pos()
	caret_pos.x -= text_edit.size.x / 2 
	pop_obj.position = caret_pos
	pop_obj.position.y -= pop_obj.pivot_offset.y * FixY
	pop_obj.modulate.a = 1.0
	pop_obj.scale = Vector2(1.5, 1.5)
	add_child(pop_obj)

	# 设定动画参数
	pop_obj.start_pos = pop_obj.position
	pop_obj.velocity = Vector2(randf_range(-30, 30), -150)
	pop_obj.gravity = 500
	pop_obj.lifetime = 1.5
	pop_obj.rot_speed = randf_range(0.5, 1.5)
	
	if randf() > 0.5:
		pop_obj.rot_dir = 1
	else:
		pop_obj.rot_dir = -1

	# 启动动画
	pop_obj.start_effect()

func smoothstep(edge0: float, edge1: float, x: float) -> float:
	x = clamp((x - edge0) / (edge1 - edge0), 0.0, 1.0)
	return x * x * (3.0 - 2.0 * x)

func _show_powder_warning():
	# 显示警告效果（示例：屏幕抖动+红色提示）
	var tween = create_tween()
	tween.tween_property(self, "modulate", Color.RED, 0.1)
	tween.tween_property(self, "modulate", Color.WHITE, 0.1)

#现在是单纯的切换，之后需要换成流程结束前不会更新状态
func _change_input_state() -> void:
	if PlayerState.CurrentInputState == PlayerState.InputState.SetBullet:
		PlayerState.CurrentInputState = PlayerState.InputState.Shoot
		text_edit.editable = false
	else:
		PlayerState.CurrentInputState = PlayerState.InputState.SetBullet
		text_edit.editable = true
	print("当前输入状态：" + str(PlayerState.CurrentInputState))
